﻿function getLayerServerFromArcgisServer(isReturnServerInfo) {
    var thisResult = null;
    var arcgisServerLayers = null;
    var arcgisLayerInfos = getJsonDataByClassName("ipt_arcgis_info_add");
    var ip = $("select[class*=ipt_arcgis_info_add][name*=RESOURCEPOSITION] option:selected").attr("ip");
    if (ip == "" || arcgisLayerInfos.ADDRESS == "") {
        layui.layer.msg("请选择提供方并输入MapServer地址");
        return;
    }
    arcgisLayerInfos.ADDRESS = arcgisLayerInfos.ADDRESS.slice(0, 1) == "/" ? arcgisLayerInfos.ADDRESS : "/" + arcgisLayerInfos.ADDRESS;
    //var ip = $("select[class*=ipt_arcgis_info_add][name*=RESOURCEPOSITION] option:selected").val();
    //检查服务地址图层是否已经注册过
    var serverExist = arcgisServerIsExist(ip, arcgisLayerInfos.ADDRESS)
    //var serverExist = arcgisServerIsExist(arcgisLayerInfos.RESOURCEPOSITION, arcgisLayerInfos.ADDRESS);
    if (serverExist > 0) {
        if (!confirm("检测到系统中已存在相同服务地址，继续提交将覆盖已存在的服务信息！确认继续吗？")) {
            clearArcgisServerList();
            return;
        }
    }
    var arcgisServerURL = "http://" + ip + arcgisLayerInfos.ADDRESS + "/layers?f=pjson";
    //http://localhost:6080 /arcgis/rest/services/BBXSERVER/BBX/MapServer /layers?f=pjson
    //arcgisServerURL = "http://localhost:6080/arcgis/rest/services/XinZhouShi/XZQ/MapServer/0/1/htmlPopup?f=pjson";
    $.ajaxSettings.async = false;
    $.ajax({
        url: arcgisServerURL,
        success: function (result) {
            arcgisServerLayers = JSON.parse(result);
            if (arcgisServerLayers.hasOwnProperty("error")) {
                layui.layer.msg("无效的Server地址，请填写正确的提供方与服务地址!",{icon:5});
                return;
            }
            else if (arcgisServerLayers.layers.length == 0) {
                layui.layer.msg("没有查找到相关图层");
                return;
            }
            else if (arcgisServerLayers.layers.length > 0) {
                thisResult = arcgisServerLayers.layers;
            }
        },
        error: function (result) {
            layui.layer.msg("无效的Server地址，请填写正确的提供方与服务地址!",{icon:5});
            return;
        }
    });
    $.ajaxSettings.async = true; 
    if (thisResult) {
        if (thisResult.length > 0) {
            if (isReturnServerInfo) {
                return thisResult;
            }
            fillArcgisServerLayer(arcgisServerLayers.layers);
            fillArcgisServerLayerTable(arcgisServerLayers.layers);
        }
    }
}
//通过类名获取输入框、下拉框的值
function getJsonDataByClassName(classname){
    var thisResult={};
    var nodes=$("."+classname);
    var node=null;
    for (var i = 0; i < nodes.length; i++) {
        node=$(nodes[i]);
        thisResult[node.attr("name")] = node.val() == "null" ? "" : node.val();
    }
    return thisResult;
}
//将获取到的Arcgis图层服务展示在界面上
function fillArcgisServerLayer(arcgisServerLayers) {
    var arcgisServerLayerTable = $("#arcgisServerLayersTable");
    arcgisServerLayerTable.find("thead input[type=checkbox]").prop("checked", false);
    arcgisServerLayerTable.find("tbody").children().remove();
    var arcgisServerLayer_tr, arcgisServerLayer;
    for (var i = 0; i < arcgisServerLayers.length; i++) {
        arcgisServerLayer = arcgisServerLayers[i];
        if (arcgisServerLayer.type=="Group Layer") {
            arcgisServerLayer_tr = "<tr serverid='" + arcgisServerLayer.id + "'>"
                + "<td style='width:50px;'></td>"
                + "<td style='width:100px;'>" + (i + 1) + "</td>"
                + "<td style='width:100px;'>" + arcgisServerLayer.id + "</td>"
                + "<td style='width:200px;' class='arcgisname'>" + arcgisServerLayer.name + "</td>"
                + "<td style='width:200px;'><input type='text' class='arcgisalias' name='LAYERALIAS' layerServerID='" + arcgisServerLayer.id + "' value='" + arcgisServerLayer.name + "' oninput='fillLayerName(this)' maxlength='20'/></td>"
                + "<td style='width:100px;'></td>"
                + "</tr>";
        }
        else {
            arcgisServerLayer_tr = "<tr serverid='" + arcgisServerLayer.id + "'>"
                + "<td style='width:50px;padding-left:20px;'><input type='checkbox' class='checkArcgisServer arcgisserver' value='" + arcgisServerLayer.id + "'/></td>"
                + "<td style='width:100px;'>" + (i + 1) + "</td>"
                + "<td style='width:100px;'>" + arcgisServerLayer.id + "</td>"
                + "<td style='width:200px;' class='arcgisname'>" + arcgisServerLayer.name + "</td>"
                + "<td style='width:200px;'><input type='text' class='arcgisalias' name='LAYERALIAS' layerServerID='" + arcgisServerLayer.id + "' value='" + arcgisServerLayer.name + "' oninput='fillLayerName(this)' maxlength='20'/></td>"
                + "<td style='width:100px;'><input type='checkbox' class='checkArcgisQuery arcgisquery' value=''/></td>"
                + "</tr>";
        }
        //onchange='checkArcgisUnique(this)'
        arcgisServerLayerTable.find("tbody").append(arcgisServerLayer_tr);
    }
    if (arcgisServerLayers.length > 0) {
        $("#ipt_selectAllServer").click();
        $("#ipt_selectAllQuery").click();
    }
    $(".checkArcgisServer,.checkArcgisQuery").click(function (evt) {
        var target_all = null, target_child = null;
        if ($(evt.currentTarget).hasClass("arcgisserver")) {
            target_all = $("#ipt_selectAllServer");
            target_child = $(".checkArcgisServer");
        }
        else if ($(evt.currentTarget).hasClass("arcgisquery")) {
            target_all = $("#ipt_selectAllQuery");
            target_child = $(".checkArcgisQuery");
        }
        else {
            return;
        }
        if (!$(evt.currentTarget)[0].checked) {
            if (target_all[0].checked) {
                target_all[0].checked = false;
            }
        }
        else {
            new Promise(function (resolve) {
                for (var i = 0; i < target_child.length; i++) {
                    if (!target_child[i].checked) {
                        return;
                    }
                }
                resolve();
            }).then(function () {
                if (!target_all[0].checked) {
                    target_all[0].checked = true;
                }
            });
        }
    })
}
//生成图层别名对应的图层名
function fillLayerName(node) {
    $(node).parent().parent().find(".arcgisname").text(pinyin.getCamelChars(trimStr(node.value)));
}
//服务全选
function selectAllServer(node) {
    if (node.checked) {
        $('.checkArcgisServer').each(function () {
            if (!$(this)[0].checked) {
                $(this).click();
            }
        });
    }
    else {
        $('.checkArcgisServer').each(function () {
            if ($(this)[0].checked) {
                $(this).click();
            }
        });
    }
}
//可查全选
function selectAllQuery(node) {
    if (node.checked) {
        $('.checkArcgisQuery').each(function () {
            if (!$(this)[0].checked) {
                $(this).click();
            }
        });
    }
    else {

        $('.checkArcgisQuery').each(function () {
            if ($(this)[0].checked) {
                $(this).click();
            }
        });
    }
}
//Arcgis批量接入服务保存
function saveArcgisLayerInfo(classname) {
    var serverName = $("input[class*=ipt_arcgis_info_add][name*=LAYERALIAS]").val();
    $("#arcgisServerLayersTable tbody .error").remove();
    if (!serverName) {//服务名为空验证
        layui.layer.msg("请输入服务名称");
        return;
    }
    if (!checkInputRight("div_add_arcgis_info")) {//输入项正确性验证
        return;
    }
    if ($("#arcgisServerLayersTable tbody tr").length == 0 || $(".checkArcgisServer:checked").length==0) {//待注册项验证
        layui.layer.msg("请选择需要注册的图层服务");
        return;
    }
    if ($("#arcgisServerLayersTable tbody .arcgisname:empty").length > 0) {
        layui.layer.msg("请完善图层名");
        return;
    }
    if (!checkArcgisUnique()) {
        layui.layer.msg("图层名称不可重复");
        return;
    }
    if (!getNodeByID("ipt_catalogattr").value) {//资源目录验证
        layui.layer.msg("请选择所属目录");
        //openAddDiv("catalog");
        return;
    }
    if (!getNodeByID("ipt_XZQHDM").value) {//所属行政区验证
        layui.layer.msg("请选择所属区域");
       // openAddDiv("xzqh");
        return;
    }
    var baseGUID = getGUID();
    var arcgisLayerInputInfos = getJsonDataByClassName(classname);
    arcgisLayerInputInfos["LAYERNAME"] = pinyin.getCamelChars(arcgisLayerInputInfos.LAYERALIAS);//服务图层名称
    //arcgisLayerInputInfos["RESOURCEPOSITION"] = $("select[class*=ipt_arcgis_info_add][name*=RESOURCEPOSITION] option:selected").text();//资源服务器
    arcgisLayerInputInfos["RESOURCEPOSITION"] = $("select[class*=ipt_arcgis_info_add][name*=RESOURCEPOSITION] option:selected").val();//资源服务器

    var arcgisServerLayerInfos = getLayerServerFromArcgisServer(true);//获取Arcgis服务信息

    //资源目录信息
    var catalogID = $("#ipt_catalogID").val();
    arcgisLayerInputInfos["CATALOGID"] = catalogID;
    var catalogAttrArr = $("#ipt_catalogattr").val().split("|");
    arcgisLayerInputInfos["ATTR_A"] = catalogAttrArr[0];
    arcgisLayerInputInfos["ATTR_B"] = "";
    arcgisLayerInputInfos["ATTR_C"] = "";
    arcgisLayerInputInfos["ATTR_D"] = "";
    if (catalogAttrArr.length > 1) {
        arcgisLayerInputInfos.ATTR_B=catalogAttrArr[1];
    }
    if (catalogAttrArr.length > 2) {
        arcgisLayerInputInfos.ATTR_C=catalogAttrArr[2];
    }
    if (catalogAttrArr.length > 3) {
        arcgisLayerInputInfos.ATTR_D=catalogAttrArr[3];
    }

    //行政区划代码
    var xzqhDM = $("#ipt_XZQHDM").val();
    arcgisLayerInputInfos["AREA"] = xzqhDM.length == 6 ? xzqhDM : (xzqhDM.length == 4 ? xzqhDM + "00" : (xzqhDM.length
        == 2 ? xzqhDM + "0000" : "000000"));

    //其他共同属性
    arcgisLayerInputInfos["PRJ"] = arcgisServerLayerInfos[0].extent.spatialReference.latestWkid ? ("EPSG:" + arcgisServerLayerInfos[0].extent.spatialReference.latestWkid) : ("wkid:" + arcgisServerLayerInfos[0].extent.spatialReference.wkid);
    arcgisLayerInputInfos["SERVICETYPE"] = "tile";
    arcgisLayerInputInfos["SOURCE"] = "tilearcgisrest";
    arcgisLayerInputInfos["STATUS"] = "online";
    arcgisLayerInputInfos["PARAMETERS"] = "";
    arcgisLayerInputInfos["SERVERTYPE"] = "arcgis";
    arcgisLayerInputInfos["CHECKSTATUS"] = "1";
    arcgisLayerInputInfos["GUID"] = baseGUID+"_";
    arcgisLayerInputInfos["fields"] = {};

    var arcgisLayerInfos = {};
    arcgisLayerInfos[baseGUID] = $.extend({}, arcgisLayerInputInfos);
    arcgisLayerInfos[baseGUID]['parent'] = 1;
    //console.log(arcgisLayerInputInfos);

    //获取地图等级划分信息
    var MapResolutions = getMapResolutions("EPSG:3857", 22);

    //声明循环中的变量
    var arcgisServerList = $("#arcgisServerLayersTable tbody tr");
    var arcgisLayerServer = null, serverid = null, tr_arcgisServer = null, layerGUID = null;
    var centerPoint, serverEvent, calcResult;
    for (var i = 0; i < arcgisServerList.length; i++) {
        tr_arcgisServer = $(arcgisServerList[i]);
        if (tr_arcgisServer.find(".checkArcgisServer").length>0&&tr_arcgisServer.find(".checkArcgisServer")[0].checked) {
            serverid = tr_arcgisServer.attr("serverid");
            if (arcgisLayerInfos[baseGUID].PARAMETERS=="") {
                arcgisLayerInfos[baseGUID].PARAMETERS = serverid;
            }
            else {
                arcgisLayerInfos[baseGUID].PARAMETERS += ("," + serverid);
            }
            arcgisLayerServer = arcgisServerLayerInfos[serverid];//被选中的server信息
            layerGUID = baseGUID+"_" + (serverid < 10 ? "00" + serverid : (serverid < 100 ? "0" + serverid : serverid));
            arcgisLayerInfos[layerGUID] = $.extend({}, arcgisLayerInputInfos);//继承公共属性
            arcgisLayerInfos[layerGUID]["ID"] = serverid;//图层服务ID
            arcgisLayerInfos[layerGUID].LAYERALIAS = tr_arcgisServer.find(".arcgisalias").val();//图层别名
            arcgisLayerInfos[layerGUID].LAYERNAME = tr_arcgisServer.find(".arcgisname").text();//图层名
            arcgisLayerInfos[layerGUID]["ISQUERY"] = tr_arcgisServer.find(".arcgisquery")[0].checked ? "true" : "false";//是否可查
            arcgisLayerInfos[layerGUID]["GUID"] = layerGUID;//图层GUID
            arcgisLayerInfos[layerGUID]["ORDERINDEX"] = (parseInt(serverid) + 1) + "";//图层排序
            serverEvent = arcgisLayerServer.extent;
            calcResult = calcServerInfoWithExtent(arcgisLayerServer.extent, "4326");//计算地图中心，缩放级别等信息
            arcgisLayerInfos[layerGUID]["PRJ"] = calcResult.prj;//服务投影
            //arcgisLayerInfos[layerGUID]["PRJ"] = arcgisLayerServer.extent.spatialReference.latestWkid ? ("EPSG:" + arcgisLayerServer.extent.spatialReference.latestWkid) : ("wkid:" + arcgisLayerServer.extent.spatialReference.wkid);
            arcgisLayerInfos[layerGUID]["POSITION"] = calcResult.centerPoint_result[0].toFixed(3) + "," + calcResult.centerPoint_result[1].toFixed(3);
            for (var j = 0; j < MapResolutions.length; j++) {
                if (j > 15) {
                    arcgisLayerInfos[layerGUID].POSITION += ",15";
                    break;
                }
                else {
                    if (calcResult.offset_3857 > MapResolutions[j]) {
                        arcgisLayerInfos[layerGUID].POSITION += "," + j;
                        break;
                    }
                }
            }

            //图层字段信息
            arcgisLayerInfos[layerGUID]["fields"] = getServerFieldInfo(arcgisLayerServer, layerGUID, arcgisLayerInfos[layerGUID].LAYERNAME);

        }
        else {
            continue;
        }
    }
    var metaData;
    metaData = {
        "SERVICEVERSION": arcgisLayerInputInfos.SERVICEVERSION,
        "GEODETICDATUMCOORDINATE": arcgisLayerInputInfos.GEODETICDATUMCOORDINATE,
        "HEIGHTDATUM": arcgisLayerInputInfos.HEIGHTDATUM,
        "CENTRALMERIDIAN": arcgisLayerInputInfos.CENTRALMERIDIAN,
        "WESTLON": arcgisLayerInputInfos.WESTLON,
        "NORTHLAT": arcgisLayerInputInfos.NORTHLAT,
        "EASTLON": arcgisLayerInputInfos.EASTLON,
        "SOUTHLAT": arcgisLayerInputInfos.SOUTHLAT,
        "DATARELEASEUNIT": arcgisLayerInputInfos.DATARELEASEUNIT,
        "SERVICERELEASETIME": arcgisLayerInputInfos.SERVICERELEASETIME,
        "CONTACTPHONENUMBER": arcgisLayerInputInfos.CONTACTPHONENUMBER,
        "HEADOFUNIT": arcgisLayerInputInfos.HEADOFUNIT
    };
    metaData = JSON.stringify(metaData);
    var strLayerServersInfo = JSON.stringify(arcgisLayerInfos);
    var configInfo = InitialParameter("/Config.json");
    var modelURL= configInfo["modelTree"].type + '://' + configInfo["modelTree"].value;
    var portaluserno = getCookie ('portaluserno')
    $.ajax({
        type: "post",
        async: false,
        url: modelURL + "/sw/resource/insertArcgisLayersInfo",
        data: //发送到服务器的参数
            {
                //stype: "InsertArcgisLayerList",

                data: strLayerServersInfo,
                treeId: treeParam["treeId"],
                meteData: typeof (metaData) == 'string' ? metaData : JSON.stringify(metaData),
                userNo:portaluserno,
                serviceCategory: arcgisLayerInputInfos.SERVICESTYPE//服务种类
            },
        datatype: "json",
        success: function (result) {
            let data = JSON.parse(result);
            layui.layer.open({
                type: 1
                                , offset: "auto"
                                , content: '<div style="padding: 20px 100px;color: black;">' + "注册成功!" + '</div>'
                                , btn: '确定'
                                , btnAlign: 'c' //按钮居中
                                , yes: function () {
                                    layer.closeAll();
                                }
            });
        },
        error: function (err) {
            if (err.status == 405)
                layui.layer.msg(data.msg);
               // top.location.href = '/';
        }
    });
}
//清除ArcgisServer列表
function clearArcgisServerList() {
    $("#arcgisServerLayersTable tbody").empty();
    if ($("#ipt_selectAllServer")[0].checked) {//取消服务勾选
        $("#ipt_selectAllServer").click();
    }
    if ($("#ipt_selectAllQuery")[0].checked) {//取消查询勾选
        $("#ipt_selectAllQuery").click();
    }
}
//图层名唯一性检查
function checkArcgisUnique() {
    if ($("#arcgisServerLayersTable tbody .checkflag").length > 0) {
        $("#arcgisServerLayersTable tbody .checkflag").remove();
    }
    var thisResult = true;//输入项唯一
    var iptValue = {};
    var errorNode;
    $.ajaxSettings.async = false;
    $("#arcgisServerLayersTable tbody input[class*=arcgisalias]").each(function () {
        if (iptValue.hasOwnProperty(trimStr($(this).val()))) {
            thisResult = false;
            iptValue[$(this).val()].status = true;
            iptValue[$(this).val()].id.push($(this).attr("layerServerID"));
        }
        else {
            iptValue[trimStr($(this).val())] = {
                status: false,
                id: [$(this).attr("layerServerID")]
            }
        }
    });
    $.ajaxSettings.async = true;
    if (!thisResult) {
        for (var key in iptValue) {
            if (iptValue[key].status) {
                for (var j = 0; j < iptValue[key].id.length; j++) {
                    errorNode= createNode("font");
                    errorNode.className = "checkflag error";
                    errorNode.innerHTML = "✘";
                    errorNode.style = "color:red;font-size:18px;";
                    $("#arcgisServerLayersTable .arcgisalias[layerServerID=" + iptValue[key].id[j] + "]").after(errorNode);
                }
            }
        }
    }
    return thisResult;
}
//根据四至计算相关信息
function calcServerInfoWithExtent(serverExtent, outSR) {
    outSR = outSR ? "EPSG:" + outSR : "EPSG:4326";
    var thisResult = {
        centerPoint_source: null,
        centerPoint_result: null,
        extent_source: null,
        extent_result: null,
        prj: null,
        wkid: null,
        offset_3857:null
    };
    //坐标系投影
    var spatialReference = serverExtent.spatialReference;
    thisResult.prj = spatialReference.latestWkid ? ("EPSG:" + spatialReference.latestWkid) : null;
    thisResult.wkid = spatialReference.wkid ? ("wkid:" + spatialReference.wkid) : null;
    //四至范围
    thisResult.extent_source = [serverExtent.xmin, serverExtent.ymin, serverExtent.xmax, serverExtent.ymax];
    //var extentPointArr = CoordTransform(thisResult.extent_source, false, spatialReference.latestWkid);
    var extentPointArr = addProjectionTransform(thisResult.extent_source, "EPSG:"+spatialReference.latestWkid, "EPSG:4326", false);
    if (extentPointArr.code=="400") {
        alert(extentPointArr.msg);
        return;
    }
    extentPointArr = extentPointArr.result;
    thisResult.extent_result = [extentPointArr[0][0], extentPointArr[0][1], extentPointArr[1][0], extentPointArr[1][1]];
    //中心点坐标
    thisResult.centerPoint_source = [(serverExtent.xmin + serverExtent.xmax) / 2, (serverExtent.ymin + serverExtent.ymax) / 2];
    thisResult.centerPoint_result = CoordTransform(thisResult.centerPoint_source, false, spatialReference.latestWkid)[0];
    //EPSG:3857坐标系下图层x、y方向上最大偏移量
    //extentPointArr = CoordTransform(thisResult.extent_source, false, spatialReference.latestWkid, "3857");
    extentPointArr = addProjectionTransform(thisResult.extent_source, "EPSG:" + spatialReference.latestWkid, "EPSG:3857", false);
    extentPointArr = extentPointArr.result;
    var Offset_x = extentPointArr[1][0] - extentPointArr[0][0];
    var Offset_y = extentPointArr[1][1] - extentPointArr[0][1];
    thisResult.offset_3857 = (Offset_x > Offset_y ? Offset_x : Offset_y) / 1000;

    return thisResult;
    //缩放级别
    //var Offset_x = thisResult.extent_source[2] - thisResult.extent_source[0];
    //var Offset_y = thisResult.extent_source[3] - thisResult.extent_source[1];
    //var Offset_max = Offset_x > Offset_y ? Offset_x : Offset_y;
    //Offset_max = Offset_max / 1000;
    //var serverResolutions = getMapResolutions(thisResult.prj, 22);
    //console.log("offset_max:" + Offset_max);
    //console.log(serverResolutions);
    //for (var i = 0; i < serverResolutions.length; i++) {
    //    if (Offset_max > serverResolutions[i]) {
    //        thisResult.zoom = i;
    //        break;
    //    }
    //}
    
}
//坐标数组转换
function CoordTransform(pointArr,isArr, inSR, outSR) {
    inSR = inSR ? "EPSG:" + inSR : "EPSG:3857";
    outSR = outSR ? "EPSG:" + outSR : "EPSG:4326";
    var thisResult = new Array();
    if (isArr) {
        for (var i = 0; i < pointArr.length; i++) {
            thisResult.push(ol.proj.transform(pointArr[i], inSR, outSR));
        }
    }
    else {
        for (var i = 0; i < pointArr.length / 2; i++) {
            thisResult.push(ol.proj.transform([pointArr[2 * i], pointArr[2 * i + 1]], inSR, outSR));
        }
    }
    return thisResult;
}
function addProjectionTransform(pointArr, inSR, outSR, isPointArr) {
    inSR = inSR ? inSR : "EPSG:3857";
    outSR = outSR ? outSR : "EPSG:4326";
    var thisResult = {
        code: "200",
        msg: "转换成功",
        inSR: inSR,
        outSR: outSR,
        result: []
    };
    var prjConfig = InitialParameter("../../MapServer/Json/Projection.json");
    //var prjConfig = null;
    //$.ajaxSettings.async = false;
    //$.getJSON("../../MapServer/Json/Projection.json", function (result) {
    //    prjConfig = JSON.parse(result);
    //});
    //$.ajaxSettings.async = true;
    var projections = prjConfig.projections;
    if (projections.hasOwnProperty(inSR) && projections.hasOwnProperty(outSR)) {
        var projectionIn, projectionOut;
        if (inSR != "EPSG:3857" && inSR != "EPSG:4326") {
            proj4.defs(inSR, projections[inSR].proj4);
            projectionIn = new ol.proj.Projection({
                code: inSR
            });
            ol.proj.addProjection(projectionIn);
        }
        if (outSR != "EPSG:3857" && outSR != "EPSG:4326") {
            proj4.defs(outSR, projections[outSR].proj4);
            projectionOut = new ol.proj.Projection({
                code: outSR
            });
            ol.proj.addProjection(projectionOut);
        }
        ol.proj.addCoordinateTransforms(inSR, outSR,
            function (coordinate) {
                return proj4(inSR, outSR, coordinate);
            },
            function (coordinate) {
                return proj4(outSR, inSR, coordinate);
            });
    }
    else {
        thisResult.code = "400";
        thisResult.msg = "无法识别的坐标系(";
        if (!projections.hasOwnProperty(inSR)) {
            thisResult.result.push(inSR);
            thisResult.msg += inSR;
        }
        if (!projections.hasOwnProperty(outSR)) {
            thisResult.result.push(outSR);
            thisResult.msg += ("," + outSR);
        }
        thisResult.msg += ")";
        return thisResult;
    }
    if (isPointArr) {
        for (var i = 0; i < pointArr.length; i++) {
            thisResult.result.push(ol.proj.transform(pointArr[i], inSR, outSR));
        }
    }
    else {
        for (var i = 0; i < pointArr.length / 2; i++) {
            thisResult.result.push(ol.proj.transform([pointArr[2 * i], pointArr[2 * i + 1]], inSR, outSR));
        }
    }
    //var code_outSR = ol.proj.transform([112.863, 42.417], inSR, outSR);
    //console.log(thisResult);
    return thisResult;
}
//获取格网等级
function getMapResolutions(prj,gridLevel,mapMaxZoom) {
    prj = prj ? prj : "EPSG:3857";
    gridLevel = gridLevel ? gridLevel : 22;
    mapMaxZoom = mapMaxZoom ? mapMaxZoom : gridLevel;

    var gridNames = [];
    var projExtent = ol.proj.get(prj).getExtent();
    var startResolution = ol.extent.getWidth(projExtent) / 256;
    var resolutions = new Array(mapMaxZoom);
    for (i = 1; i < gridLevel; i++) {
        gridNames[i] = prj + ":" + i;
        resolutions[i] = startResolution / Math.pow(2, i);
    }
    return resolutions;
}
//获取服务字段信息
function getServerFieldInfo(serverInfo, layerGUID, layerName) {
    var thisResult = {};
    var fieldsInfo = serverInfo.fields;
    if (fieldInfo==null) {
        fieldsInfo=[];
    }
    var fieldInfo = null, fieldType;
    for (var i = 0; i < fieldsInfo.length; i++) {
        fieldType = null;
        fieldInfo = fieldsInfo[i];
        if (fieldInfo.name.toLowerCase()=="shape") {
            continue;
        }
        thisResult[fieldInfo.name] = {};

        thisResult[fieldInfo.name]["FIELDNAME"] = fieldInfo.name;
        thisResult[fieldInfo.name]["FIELDALIAS"] = fieldInfo.alias;
        switch (fieldInfo.type) {
            case "esriFieldTypeOID":
            case "esriFieldTypeInteger":
                fieldType = "Int";
                break;
            case "esriFieldTypeDouble":
                fieldType = "Float"
                break;
            case "esriFieldTypeString":
            default:
                fieldType = "Char";
                break;
        }
        switch (fieldInfo.name.toLowerCase()) {
            case "objectid":
            case "fid":
                thisResult[fieldInfo.name]["ISQUERY"] = "false";
                break;
            default:
                thisResult[fieldInfo.name]["ISQUERY"] = "true";
                break;
        }

        thisResult[fieldInfo.name]["TYPE"] = fieldType;
        thisResult[fieldInfo.name]["ORDERINDEX"] = i;
        thisResult[fieldInfo.name]["GUID"] = getGUID();
        thisResult[fieldInfo.name]["LAYERGUID"] = layerGUID;
        thisResult[fieldInfo.name]["LAYERNAME"] = layerName;
    }
    return thisResult;
}
//arcgis服务重复性验证
function arcgisServerIsExist(ip,address) {
    //var thisResult = false;
    //var getExistServerTable = `select count(decode(b.id,null,0,b.id))as num from tb_dataserver_layer b where b.guid in (select bb.resourceid
    //                                                from (select a.name
    //                                                      from tb_database_connection a
    //                                                     where a.ip = '`+ip.split(":")[0]+`'
    //                                                       and a.port = '`+ip.split(":")[1]+`') aa
    //                                              left join tb_resource bb
    //                                                on aa.name = bb.position
    //                                             where bb.address =
    //                                                   '`+address+`'
    //                                               and bb.zylx = '2') `+(id?` and id='`+id+`' `:``);

    //var queryResult = GetDatatable(getExistServerTable);
    //if (queryResult) {
    //    if (parseInt(JSON.parse(queryResult)[0].NUM)>0) {
    //        thisResult=true;
    //    }
    //}
    //return thisResult;
    var thisResult = null;
    var configInfo = InitialParameter("/Config.json");
    var modelURL = configInfo["modelTree"].type + '://' + configInfo["modelTree"].value;
    $.ajax({
        type: "post",
        async: false,
        url: modelURL + "/sw/resource/getArcgisResource",
        data: //发送到服务器的参数
            {
                position: ip,
                address:address
            },
        datatype: "json",
        success: function (result) {
            let data = JSON.parse(result);
            thisResult = data.data;
        },
        error: function (err) {
            if (err.status == 405)
                layui.layer.msg(data.msg, { time: 1000, icon: 5, shift: 6 });
        }
    });
    return thisResult;
}